package com.sm.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.util.ObjectUtil;
import com.sm.model.*;
import com.sm.service.*;
import com.sm.util.PageBean;
import com.sm.util.PageResult;
import com.sm.vo.OrderVO;
import com.sm.wx.vo.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sm.util.Msg;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/order")
public class OrderController {

	@Autowired
	private UserService userService;

	@Autowired
	private OrderService orderService;

	@Autowired
	private UserAddressService userAddressService;

	@Autowired
	private GoodsService goodsService;

	@Autowired
	private ShopCarService shopCarService;


	/**
	 * 二次订单
	 */
	@RequestMapping("/againCreateOrder")
	@ResponseBody
	public Msg againCreateOrder(HttpServletRequest request, OrderVO orderVO) {

		Integer userId = orderVO.getUserId();
		Integer payType = orderVO.getPayType();
		User user = userService.selectByPrimaryKey(userId);
		if (user == null) {
			return Msg.fail().add("msg", "用户不存在");
		}
		if (payType == null || (payType != 1 && payType != 2)) {
			return Msg.fail().add("msg", "请选择付款方式");
		}
		Order order1 = orderService.selectByPrimaryKey(orderVO.getOrderId());
		if (order1 == null) {
			return Msg.fail().add("msg", "订单不存在");
		}
		if (order1.getOrderStatus() != -2) {
			return Msg.fail().add("msg", "订单状态错误");
		}
		AjaxResult orders = orderService.againCreateOrder(request, orderVO);
		return Msg.success(orders);
	}

	/**
	 * 创建订单
	 */
	@RequestMapping("/createOrder")
	@ResponseBody
	public Msg createOrder(HttpServletRequest request, OrderVO orderVO) {
		Integer userId = orderVO.getUserId();
		Integer userAddressId = orderVO.getUserAddressId();
		Integer payType = orderVO.getPayType();
		User user = userService.selectByPrimaryKey(userId);
		UserAddress userAddress = userAddressService.selectByPrimaryKey(userAddressId);
		if (user == null) {
			return Msg.fail().add("msg", "用户不存在");
		}
		if (userAddress == null) {
			return Msg.fail().add("msg", "请选择收获地址");
		}
		if (payType == null || (payType != 1 && payType != 2)) {
			return Msg.fail().add("msg", "请选择付款方式");
		}
		//购物车下单
		if (orderVO.getShopCarIds() != null && orderVO.getShopCarIds().size() > 0) {
			for (Integer shopCarId : orderVO.getShopCarIds()) {
				ShopCar shopCar = shopCarService.selectByPrimaryKey(shopCarId);
				if(shopCar==null) return Msg.fail().add("msg", "购物车数据不存在");
				Goods goods = goodsService.selectByPrimaryKey(shopCar.getGoodsId());
				if (goods == null) {
					return Msg.fail().add("msg", "商品不存在");
				} else {
					if (goods.getGoodsStock() < shopCar.getGoodsNumber()) {
						return Msg.fail().add("msg", "商品库存不足");
					}
				}
			}
		} else {
			//单商品下单
			Goods goods = goodsService.selectByPrimaryKey(orderVO.getGoodsId());
			if (goods == null) {
				return Msg.fail().add("msg", "请选择商品");
			}else {
				if (goods.getGoodsStock() < orderVO.getNum()) {
					return Msg.fail().add("msg", "商品库存不足");
				}
			}
			if (orderVO.getNum() == null || orderVO.getNum() < 1) {
				return Msg.fail().add("msg", "请选择正确的数量");
			}
		}
		AjaxResult order = orderService.createOrder(request, orderVO);
		return Msg.success(order);
	}


	/**
	 * 订单详情
	 * @param orderId
	 * @return
	 */
	@RequestMapping("/orderDetail")
	@ResponseBody
	public Msg orderDetail(Integer orderId) {
		Order order = orderService.selectByPrimaryKey(orderId);
		if(order==null) {
			return Msg.fail().add("msg", "参数不为空！");
		}
		User user = userService.selectUserById(order.getUserId());
		if (ObjectUtil.isNotEmpty(user)){
			order.setUserName(user.getNickName());
			order.setUserPhone(user.getPhone());
		}
		UserAddress userAddress = userAddressService.selectByPrimaryKey(order.getUserAddressId());
		if (ObjectUtil.isNotEmpty(userAddress)){
			order.setUserAddress(userAddress.getUserAddress());
		}
		return Msg.success(order);
	}


	/**
	 * 首页订单数量
	 * @param userId
	 * @return
	 */
	@RequestMapping("/orderCount")
	@ResponseBody
	public Msg orderCount(Integer userId) {
		if(userId==null) {
			return Msg.fail().add("msg", "参数不为空！");
		}

		Map<String, Integer> result = new HashMap<>();
		int all = orderService.selectCountByType(-4, userId);
		int waitPay = orderService.selectCountByType(-2, userId);
		int waitSend = orderService.selectCountByType(0, userId);
		int waitConfirm = orderService.selectCountByType(1, userId);
		int finish = orderService.selectCountByType(4, userId);
		result.put("all", all);//全部订单
		result.put("waitPay", waitPay);//代付款
		result.put("waitSend", waitSend);//待发货
		result.put("waitConfirm", waitConfirm);//待收货
		result.put("finish", finish);//已完成
		return Msg.success(result);
	}

	/**
	 * 查订单
	 * @param userId
	 * @param orderStatus 订单状态 -4全部 -2待支付 -1取消 0待发货 1待收货 2退款中 3退款成功 4订单完成
	 * @return
	 */
	@RequestMapping("/selectOrder")
	@ResponseBody
	public Msg selectOrder(Integer userId, Integer orderStatus, PageBean pageBean) {
		if(userId==null) {
			return Msg.fail().add("msg", "参数不为空！");
		}
		if(orderStatus==null) orderStatus = -4;
		PageResult list = orderService.selectOrderByOrderStatus(userId, orderStatus,pageBean);
//		List<Order> list2 = orderService.selectOrderByOrderStatus(userId, -1);
//		List<Order> list3 = orderService.selectOrderByOrderStatus(userId, 0);
//		List<Order> list4 = orderService.selectOrderByOrderStatus(userId, 1);
		return Msg.success().add("list",list);
	}

	/**
	 * 确认收货
	 * @param orderId
	 * @return
	 */
	@RequestMapping("/confirmOrder")
	@ResponseBody
	public Msg confirmOrder(Integer orderId) {
		if(orderId==null) {
			return Msg.fail();
		}
		Order order = orderService.selectByPrimaryKey(orderId);
		if (order == null || order.getOrderStatus() != 1) {
			return Msg.fail().add("msg", "订单状态错误");
		}
		order.setOrderStatus(4);
		int a = orderService.updateByPrimaryKeySelective(order);
		//加商品销量
		Integer goodsId = order.getGoodsId();
		Integer goodsNumber = order.getGoodsNumber();
		Goods goods = goodsService.selectByPrimaryKey(goodsId);
		goods.setGoodsSales(goods.getGoodsSales() + goodsNumber);
		goodsService.updateById(goods);
		if(a==1) {
			return Msg.success().add("msg", "确认成功！");
		}else {
			return Msg.fail();
		}

	}


	/**
	 * 申请退款
	 * @param orderId
	 * @param remark	原因
	 * @return
	 */
	@RequestMapping("/applyRefund")
	@ResponseBody
	public Msg applyRefund(Integer orderId,String remark) {
		if(orderId==null) {
			return Msg.fail().add("msg", "参数不为空");
		}
		Order order = orderService.selectByPrimaryKey(orderId);
		if (order == null || order.getOrderStatus() != 0) {
			return Msg.fail().add("msg", "订单状态错误");
		}
		order.setOrderStatus(2);
		order.setRemark(remark);
		int a = orderService.updateByPrimaryKeySelective(order);
		if(a==1) {
			return Msg.success();
		}else {
			return Msg.fail();
		}
	}

	/**
	 * 取消订单
	 * @param orderId
	 * @param remark 原因
	 * @return
	 */
	@RequestMapping("/cancelOrder")
	@ResponseBody
	public Msg cancelOrder(@RequestParam("orderId") Integer orderId,  String remark) {
		if(orderId==null) {
			return Msg.fail().add("msg", "参数不为空");
		}
		Order order = orderService.selectByPrimaryKey(orderId);
		if (order == null || order.getOrderStatus() != -2) {
			return Msg.fail().add("msg", "订单状态错误");
		}
		order.setOrderStatus(-1);
		order.setRemark(remark);
		//加库存
		Goods goods = goodsService.selectByPrimaryKey(order.getGoodsId());
		goods.setGoodsStock(goods.getGoodsStock() + order.getGoodsNumber());
		goodsService.updateById(goods);

		int a = orderService.updateByPrimaryKeySelective(order);
		if(a==1) {
			return Msg.success();
		}else {
			return Msg.fail();
		}
	}
}
